package com.xx.cloud.pay.result;

import org.apache.commons.codec.binary.Base64;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

public class ImagesUtils {


    /**
     * 文件BufferedImage类型转BASE64
     *
     * @param bufferedImage
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节


        String png_base64 = java.util.Base64.getEncoder().encodeToString(bytes);

        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return "data:image/png;base64," + png_base64;

    }

    /**
     * 文件File类型转BASE64
     *
     * @param file
     * @return
     */
    public static String fileToBase64(File file) {
        return "data:image/png;base64," + Base64.encodeBase64String(fileToByte(file));
    }

    /**
     * 文件File类型转byte[]
     *
     * @param file
     * @return
     */
    private static byte[] fileToByte(File file) {
        byte[] fileBytes = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileBytes;
    }

    public static void main(String[] args) throws IOException {
        String url = "https://file.ewbang.com/static/images/logo.png";
        BufferedImage bufferedImage = ImageIO.read(new URL(url));

    }


}
